class Solution(object):
    def maximalSquare(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        if not matrix or not matrix[0]:
            return 0
        
        m, n = len(matrix), len(matrix[0])
        
        # 创建 dp 数组，dp[i][j] 表示以 (i,j) 为右下角的最大正方形边长
        dp = [[0] * n for _ in range(m)]
        max_side = 0
        
        # 填充 dp 数组
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == '1':
                    if i == 0 or j == 0:
                        # 边界情况
                        dp[i][j] = 1
                    else:
                        # 状态转移方程
                        dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
                    
                    # 更新最大边长
                    max_side = max(max_side, dp[i][j])
        
        # 返回面积
        return max_side * max_side

# 如果需要测试，可以添加以下代码
def test_solution():
    solution = Solution()
    
    # 示例 1
    matrix1 = [["1","0","1","0","0"],
               ["1","0","1","1","1"],
               ["1","1","1","1","1"],
               ["1","0","0","1","0"]]
    result1 = solution.maximalSquare(matrix1)
    print("示例 1: " + str(result1))  # 输出: 4
    
    # 示例 2
    matrix2 = [["0","1"],
               ["1","0"]]
    result2 = solution.maximalSquare(matrix2)
    print("示例 2: " + str(result2))  # 输出: 1
    
    # 示例 3
    matrix3 = [["0"]]
    result3 = solution.maximalSquare(matrix3)
    print("示例 3: " + str(result3))  # 输出: 0

# 如果在本地运行测试
if __name__ == "__main__":
    test_solution()
